﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using ARS.Control.Attributes;
using ARS.Control.Custom.DataPaging.Attributes;
using ARS.Control.Custom.DataPaging.Widget;
using ARS.Control.Custom.Entity.Widget;
using ARS.Control.Factory;
using ARS.PublicTool.DataHandle;

namespace ARS.Control.Request
{
    public class Action : IHttpHandler
    {
        /// <summary>
        /// 您将需要在您网站的 web.config 文件中配置此处理程序，
        /// 并向 IIS 注册此处理程序，然后才能进行使用。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // 如果无法为其他请求重用托管处理程序，则返回 false。
            // 如果按请求保留某些状态信息，则通常这将为 false。
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string control = context.Request.QueryString["control"];
            if (string.IsNullOrEmpty(control))
            {
                return;
            }
            if (control == "DataPaging")
            {
                //new ARS.Control.Custom.DataPaging.Request.Action().ProcessRequest(context);
                string action = context.Request.Form["action"];
                if (action != null)
                {
                    string code = context.Request.QueryString["code"];

                    DataPagingDb dbModel = ARS.Control.Custom.DataPaging.Attributes.DataPagingDb.GetModel(code);
//                    Interface.IUser user = UserFactory.CreateUser();
//
//                    string userId = user.GetUserInfo().Id.ToString();
//                    
//                    //获取datapaging model
//                    DataBase.Provider.IDataPagingProvider dataProvider = ARS.DataBase.Provider.DataPagingProvider.GetInstance();
//                    DataPagingDb dbModel;
//                    DataPagingQueryModel queryModel = new DataPagingQueryModel();
//                    queryModel.UserId = userId;
//                    queryModel.ClassName = code;
//
//                    dbModel = dataProvider.GetDataPagingDbModel(queryModel);

                    if (action == "getlist")
                    {
                        string pageIndex = context.Request.Form["PageIndex"] ?? "1";
                        string orderIndex = context.Request.Form["OrderIndex"] ?? "-1";
                        if (orderIndex != "-1")
                        {
                            dbModel.DbSelect.OrderField = dbModel.DbOperat.OrderListItem[Int32.Parse(orderIndex)];
                        }
                        dbModel.DbSelect.PageIndex = Int32.Parse(pageIndex);
                        context.Response.Write(Factory.Dp_HtmlHelperFactory.CreateHtmlHelper().GetTableHtml(dbModel));
                        return;
                    }
                    else if (action == "del")
                    {
                        string id = context.Request.Form["id"];
                        if (id != null)
                        {
                            id = Encrypt.DecryptString(id);
                            ARS.Control.Interface.IPermDataPaging perm =
                                ARS.Control.Factory.PermDataPaging.CreatePermDataPaging();
                            if (perm.CheckDelPerm(dbModel))
                            {

                            }
                            else
                            {
                                context.Response.Write(JsonSerializer.GetJson(0, "没有权限删除"));
                                return;
                            }

                            ARS.DataBase.Provider.IDbProvider dbProvider = ARS.DataBase.Provider.DbProvider.GetInstance();
                            string deleteSqlStr = null;
                            if (string.IsNullOrEmpty(dbModel.DbOperat.DeleteSql))
                            {
                                deleteSqlStr = string.Format("delete from {1} where {2}={0}", id, dbModel.DbSelect.TableName, dbModel.DbSelect.KeyField);
                            }
                            else
                            {
                                deleteSqlStr = string.Format(dbModel.DbOperat.DeleteSql,id, dbModel.DbSelect.TableName, dbModel.DbSelect.KeyField);
                            }
                            if (dbProvider.ExecuteSql(deleteSqlStr) > 0)
                            {
                                context.Response.Write(JsonSerializer.GetJson(1, "su"));
                            }
                            else
                            {
                                context.Response.Write(JsonSerializer.GetJson(0, "删除失败"));
                            }
                            return;
                        }
                    }
                    else if (action == "ExecuteOperat")
                    {
                        string index = context.Request.Form["index"];
                        if (index == null)
                        {

                        }
                        else
                        {
                            string[] list = dbModel.DbOperat.OperatSqlListItem;
                            if (list != null)
                            {

                                string sqlStr = list[Int32.Parse(index)];
                                if (sqlStr != null)
                                {
                                    string id = context.Request.Form["id"];
                                    if (!string.IsNullOrEmpty(id))
                                    {
                                        id = Encrypt.DecryptString(id);
                                        sqlStr = sqlStr.Replace("{0}", id);
                                    }
                                    if (sqlStr.Contains("{{Text-"))
                                    {
                                        //Regex regex_field = new Regex("");
                                        //MatchCollection matchs = regex_field.Matches(sqlStr);
                                        sqlStr = Factory.Dp_HtmlHelperFactory.CreateHtmlHelper().OperatPostParams(sqlStr);
                                    }
                                    ARS.DataBase.Provider.IDbProvider dbProvider = ARS.DataBase.Provider.DbProvider.GetInstance();
                                    int count = dbProvider.ExecuteSql(sqlStr);
                                    context.Response.Write(JsonSerializer.GetJson(count, index));
                                }
                            }
                        }
                    }
                }
            }
            else if (control == "SelectLinkage")
            {
                string action = context.Request.Form["action"];
                if (action == "getson")
                {
                    string index = context.Request.Form["index"] ?? "0";
                    int indexInt = Int32.Parse(index);
                    string id = context.Request.Form["id"] ?? "0";

                    DataBase.Provider.IDbProvider dbProvider = DataBase.Provider.DbProvider.GetInstance();

                    Interface.IUser user = UserFactory.CreateUser();
                    string userId = user.GetUserInfo().Id.ToString();

                    //DbDataReader dr = dbProvider.ExecuteReader("select DbSelectSLList,ParentNameFieldList from ARS_SelectLinkage where UserId=" + userId);
                    //if (dr.Read())
                    //{
                    //    string sqlList = dr["DbSelectSLList"].ToString();
                    //    sql = ARS.Control.Custom.SelectLinkage.GetSqlIndex(ref sqlList, indexInt + 1);
                    //    parentList = dr["ParentNameFieldList"].ToString();
                    //}
                    //dr.Close();
                    ARS.DataBase.ControlCustom.Custom.DbSelectLinkage dbSl = new DataBase.ControlCustom.Custom.DbSelectLinkage();
                    Custom.SelectLinkage.Attributes.SelectLinkage slModel = dbSl.GetModel(ref userId);

                    string dbSelectSLList = slModel.DbSelectSLList;
                    string sql=null;                    
                    //string parentList=slModel.ParentNameFieldList;

                    sql = Custom.SelectLinkage.Widget.SelectLinkage.GetSqlIndex(ref dbSelectSLList, indexInt + 1);

                    if (!string.IsNullOrEmpty(sql))
                    {
                        string[] parentListItem=null;
                        parentListItem = ListAndItem.GetValueListItem(parentListItem,slModel.ParentNameFieldList);
                        string parentField = parentListItem[indexInt+1];

                        string[] valueListItem = null;
                        valueListItem = ListAndItem.GetValueListItem(valueListItem, slModel.DataValueFieldList);
                        string valueField = valueListItem[indexInt + 1];

                        string[] textListItem = null;
                        textListItem = ListAndItem.GetValueListItem(textListItem, slModel.DataTextFieldList);
                        string textField = textListItem[indexInt + 1];

                        string where = string.Format(" and {0}={1}", parentField, id);
                        if (sql.Contains("order by"))
                        {
                            sql = sql.Replace("order by", where + " order by");
                        }
                        else
                        {
                            sql += where;
                        }
                        DataSet ds = dbProvider.Query(sql);
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();

                        if (!string.IsNullOrEmpty(slModel.FirstOptionValueList))
                        {
                            string[] firstvalueListItem = null;
                            firstvalueListItem = ListAndItem.GetValueListItem(firstvalueListItem, slModel.FirstOptionValueList);
                            string firstValue = firstvalueListItem[indexInt + 1];

                            string[] firstTextItem = null;
                            firstTextItem = ListAndItem.GetValueListItem(firstTextItem, slModel.FirstOptionTextList);
                            string firstText = firstTextItem[indexInt + 1];

                            sb.Append(string.Format("<option value=\"{0}\">{1}</option>", firstValue, firstText));
                        }


                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            sb.Append(string.Format("<option value=\"{0}\">{1}</option>",dr[valueField],dr[textField]));
                        }
                        context.Response.Write(sb.ToString());
                    }

                }
            }
            else if (control == "EntityModifyPanel")
            {
                string action = context.Request.QueryString["action"];
                string model = context.Request.QueryString["model"];
                if (action == "savejs")
                {
                    EntityModifyPanel entityModifyPanel = new EntityModifyPanel();
                    //
                    string assembly = ConfigurationManager.AppSettings["FieldsAssembly"];
                    object entity = ARS.PublicTool.ReflectionHelper.CreateObjectNoCache(assembly,
                        assembly +"."+ model);
                    if (entity != null)
                    {
                        entityModifyPanel.Entity = entity;

                        string keyValue = context.Request.QueryString["Id"];
                        if (!string.IsNullOrEmpty(keyValue))
                        {
                            Func<string, bool> isMum = (str) =>
                            {
                                if (str == null || str.Length == 0)
                                    return false;
                                System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
                                byte[] bytestr = ascii.GetBytes(str);
                                foreach (byte c in bytestr)
                                {
                                    if (c < 48 || c > 57)
                                    {
                                        return false;
                                    }
                                }
                                return true;
                            };
                            if (isMum(keyValue))
                            {
                                entityModifyPanel.IsEncryptKey = false;
                            }
                            else
                            {
                                entityModifyPanel.IsEncryptKey = true;
                            }                           
                            entityModifyPanel.RequestKey = "Id";
                        }

                        //entityModifyPanel.IsEncryptKey = false;
                        string message = null;
                        entityModifyPanel.ShowDialog = (Type, msg) =>
                        {
                            message = msg;
                        };
                        //string msg = entityModifyPanel.ShowDialog();
                        entityModifyPanel.InitFromJs();
                        int newId= entityModifyPanel.AddOrUpdateEntityToDb();

                        if (newId>0)
                        {
                            context.Response.Write("保存成功！");
                        }
                        else
                        {
                            context.Response.Write(message);

                        }
                    }
                    else
                    {
                        context.Response.Write("保存失败！");
                    }

                }
                //new Action().ProcessRequest(context);
            }

            else if (control == "TreeListView")
            {
                string action = context.Request.Form["action"];
                if (action == "del")
                {
                    string id = context.Request.Form["id"];
                    string tableName = context.Request.Form["TableName"];
                    //string parentName = context.Request.Form["ParentName"];
                    string keyField = context.Request.Form["key"] ?? "Id";
                    if (!string.IsNullOrEmpty(id))
                    {
                        string sql =
                            string.Format("delete from {1} where {2}={0}", Encrypt.DecryptString(id),
                                Encrypt.DecryptString(tableName), keyField);
                        DataBase.Provider.IDbProvider dbProvider = DataBase.Provider.DbProvider.GetInstance();
                        if (
                            dbProvider.ExecuteSql(sql) > 0)
                        {
                            context.Response.Write(ARS.PublicTool.DataHandle.JsonSerializer.GetJson(1, "删除成功"));
                        }
                        else
                        {
                            context.Response.Write(ARS.PublicTool.DataHandle.JsonSerializer.GetJson(0, "删除失败"));
                        }

                    }
                }
                if (action == "getlist")
                {

                }
            }

            else if (control == "ChoicesDialogForm")
            {
                context.Response.Write("aaa");
            }

            //在此写入您的处理程序实现。
        }

        #endregion
    }
}
